﻿namespace CV.Controllers.Mvc
{
    using CV.Entities.Models;
    using CV.Interfaces.Bll;
    using CV.Interfaces.Tools;
    using CV.Resources.Controller;
    using log4net;
    using System;
    using System.Linq;
    using System.Web.Mvc;

    public class LoginController : Controller
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(LoginController));

        private IFormsAuthenticationWrapper formAuthentication;
        private IMembershipWrapper membership;
        private IUserService userService;

        public LoginController(
            IUserService userService,
            IFormsAuthenticationWrapper formAuthentication,
            IMembershipWrapper membership)
        {
            this.formAuthentication = formAuthentication;
            this.membership = membership;
            this.userService = userService;
        }

        // GET: Login
        public ActionResult Index()
        {
            var newLogin = this.TempData["newLogin"] as string;
            var model = new LoginModel();

            if (!String.IsNullOrWhiteSpace(newLogin))
            {
                model.Login = newLogin;
                model.ErrorMessage = Login.PleaseLogin;
            }

            return View(model);
        }

        // POST: Login
        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            var isValid = membership.ValidateUser(model.Login, model.Password);
            if (isValid)
            {
                formAuthentication.SetAuthCookie(model.Login, model.PersistentCookie);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View(new LoginModel() { ErrorMessage = Login.Invalid });
            }
        }

        // GET: Login/Signup
        public ActionResult Signup()
        {
            return View(new SignupModel());
        }

        // POST: Login/Signup
        [HttpPost]
        public ActionResult Signup(SignupModel model)
        {
            var result = userService.Create(model.ToEntity());
            this.TempData["newLogin"] = model.Login;
            return RedirectToAction("Index");
        }

        // GET: Login/LogOut
        public ActionResult Logout()
        {
            formAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("Index");
        }
    }
}
